package handlers

import (
	"encoding/json"
	"fmt"
	"io"
	"luntan/pkg/database"
	"luntan/pkg/models"
	"net/http"
)

type ListMessage struct {
	// status: 0->success
	Status int `json:"status"`
	// say something to notfy
	Msg string `json:"msg,omitempty"`
	// pass data to js
	Data []models.List `json:"list"`
}

func Getlist(w http.ResponseWriter, r *http.Request) {
	rows, err := database.SelectList()
	msg := ListMessage{Msg: ""}
	// fmt.Println(err.Error())
	if err != nil {
		msg.Status = -1
		msg.Msg = "select list wrong"
		ListResp(w, &msg)
		return
	}
	for rows.Next() {
		var List models.List
		err := rows.Scan(&List.Id, &List.Owner, &List.Title, &List.Description, &List.Content)
		if err != nil {
			msg.Status = -1
			msg.Msg = "scan wrong"
			ListResp(w, &msg)
			return
		}
		msg.Data = append(msg.Data, List)
	}
	ListResp(w, &msg)
}

func CreateList(w http.ResponseWriter, r *http.Request) {
	List := models.List{}
	msg := ListMessage{}
	buf, err := io.ReadAll(r.Body)
	if err != nil || buf == nil {
		msg.Status = -1
		fmt.Println("reqwrong")
		msg.Msg = "invalid/nil request param"
		ListResp(w, &msg)
		return
	}

	jsonMap := make(map[string]interface{})
	err = json.Unmarshal(buf, &jsonMap)
	List.Title = jsonMap["title"].(string)
	List.Description = jsonMap["description"].(string)
	List.Content = jsonMap["content"].(string)
	// fmt.Println(List)
	if err != nil {
		msg.Status = -400
		fmt.Println("jsonwrong")
		fmt.Println(err.Error())
		msg.Msg = err.Error()
		ListResp(w, &msg)
		return
	}
	session, _ := Session_store.Get(r, "session-luntan")
	sid, _ := session.Values["sid"].(string)
	if sid == "" {
		msg.Status = -1
		msg.Msg = "login first"
		ListResp(w, &msg)
		return
	}
	List.Owner = session.Values["name"].(string)
	listid := database.InsertList(List.Owner, List.Title, List.Description, List.Content)
	err = database.CreateTable(listid)
	if err != nil {
		msg.Status = -1
		msg.Msg = "create failed"
		ListResp(w, &msg)
		return
	}
	ListResp(w, &msg)
}
